import { Ctx, Next, Auth } from '../types';

/**
 * 中间件验证请求TOKEN
 * @export
 * @param {Ctx} ctx
 * @param {Next} next
 */
export async function validatorToken(ctx: Ctx, next: Next) {
  const { headers, jwt } = ctx;
  // 判断是否需要验证 token
  if (ctx.routerliving.auth != false) {
    const token = headers['authorization'];
    if(!token) ctx.throw(400, ctx.error('authorization is undefined'));
    try {
      const userInfo = jwt.decode(token);
      ctx.auth = <Auth> userInfo;  
    } catch (error) {
      if(error.name === 'JsonWebTokenError') {
        ctx.throw(400, ctx.error('authorization error'));
      }else{
        throw error;
      };
    }
  }
  await next();
}
